#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Function:
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Sets up user data directory.
	# - Allows automated moving of user data in DietPi. Automatically generates a symlink from /mnt/dietpi_userdata to target directory if needed.
	#
	# Usage:
	# - /boot/dietpi/func/dietpi-set_userdata SOURCE_DIRECTORY TARGET_DIRECTORY | Setup user data directory, move data if needed. If TARGET_DIRECTORY='auto', auto target location. Returns 1 if failed.
	#////////////////////////////////////

	# Import DietPi-Globals --------------------------------------------------------------
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-Set_userdata'
	G_CHECK_ROOT_USER
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	EXIT_CODE=0

	# Grab input
	# - Remove trailing slashes
	SOURCE_DIRECTORY=${1%/}
	TARGET_DIRECTORY=${2%/}

	readonly FP_LOG='/var/log/dietpi-move_userdata.log'
	LOGFILE_OUTPUT_TEXT=
	FREESPACE_REQUIRED_SOURCE=0

	Run_Move_Data(){

		# Stop all running services
		/boot/dietpi/dietpi-services stop

		# Copy source to target, if it contains any files/folders
		if [[ -z $(find "$SOURCE_DIRECTORY" -maxdepth 0 -empty) ]]; then

			G_DIETPI-NOTIFY 0 "Moving your existing data from $SOURCE_DIRECTORY to $TARGET_DIRECTORY"
			G_DIETPI-NOTIFY 2 'Please wait...\n'

			# Begin transfer
			if cp -a "$SOURCE_DIRECTORY/." "$TARGET_DIRECTORY/"; then

				# Remove source
				rm -R "$SOURCE_DIRECTORY"

				# Create symlink to G_FP_DIETPI_USERDATA if required
				if [[ $TARGET_DIRECTORY != '/mnt/dietpi_userdata' ]]; then

					rm -Rf /mnt/dietpi_userdata
					ln -s "$TARGET_DIRECTORY" /mnt/dietpi_userdata

				fi

				LOGFILE_OUTPUT_TEXT="[  OK  ] Successfully moved your data from $SOURCE_DIRECTORY to $TARGET_DIRECTORY"

			else

				LOGFILE_OUTPUT_TEXT="[FAILED] Failed to copy $SOURCE_DIRECTORY/ to $TARGET_DIRECTORY."
				EXIT_CODE=1

			fi

		fi

		# Start services back up again
		/boot/dietpi/dietpi-services start

	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////

	G_DIETPI-NOTIFY 3 'DietPi Updating user data location'
	G_DIETPI-NOTIFY 2 " - From : $SOURCE_DIRECTORY"
	G_DIETPI-NOTIFY 2 " - To   : $TARGET_DIRECTORY"
	G_DIETPI-NOTIFY 2 'Please wait...'

	# Sanity checks
	# - Check for both inputs
	if [[ ! $SOURCE_DIRECTORY || ! $TARGET_DIRECTORY ]]; then

		LOGFILE_OUTPUT_TEXT="[FAILED] Please provide a source ($SOURCE_DIRECTORY) and target ($TARGET_DIRECTORY) directory for input."
		EXIT_CODE=1

	# - Check if symlink is already pointing to target directory
	elif [[ $(readlink -f /mnt/dietpi_userdata) == "$TARGET_DIRECTORY" ]]; then

		LOGFILE_OUTPUT_TEXT='[ INFO ] /mnt/dietpi_userdata is already symlinked to target directory.'

	# - Check if source directory exists
	elif [[ ! -d $SOURCE_DIRECTORY ]]; then

		LOGFILE_OUTPUT_TEXT="[FAILED] Source directory $SOURCE_DIRECTORY does not exist."
		EXIT_CODE=1

	# - Check for disallowed directory match
	elif [[ $SOURCE_DIRECTORY =~ $TARGET_DIRECTORY || $TARGET_DIRECTORY =~ $SOURCE_DIRECTORY ]]; then

		LOGFILE_OUTPUT_TEXT="[FAILED] $SOURCE_DIRECTORY and $TARGET_DIRECTORY cannot be within each other. Disallowed directory match."
		EXIT_CODE=1

	# - Only allow full filepaths
	elif [[ $SOURCE_DIRECTORY != '/'* || $TARGET_DIRECTORY != '/'* ]]; then

		LOGFILE_OUTPUT_TEXT="[FAILED] Both source ($SOURCE_DIRECTORY) and target directories ($TARGET_DIRECTORY) must contain the full filepath (eg: /mnt/drive1)"
		EXIT_CODE=1

	else

		# - Remove /mnt/dietpi_userdata symlink, if chosen as target
		[[ $TARGET_DIRECTORY == '/mnt/dietpi_userdata' && -L '/mnt/dietpi_userdata' ]] && rm /mnt/dietpi_userdata
		mkdir -p "$TARGET_DIRECTORY"

		# - Ensure we can create, write and set permissions to target directory
		if ! G_CHECK_FS_PERMISSION_SUPPORT "$TARGET_DIRECTORY"; then

			LOGFILE_OUTPUT_TEXT="[FAILED] $TARGET_DIRECTORY does not support filesystem permissions. Transfer aborted."
			EXIT_CODE=1

		else

			# - Ensure enough freespace in target
			#	"-m" => result in MiB actual disc usage, respecting disk block size, e.g. "144"
			#	Trailing slash required with "du" to correctly check symlink target in case
			FREESPACE_REQUIRED_SOURCE=$(du -sm "$SOURCE_DIRECTORY/" | mawk '{print $1}')
			if ! G_CHECK_FREESPACE "$TARGET_DIRECTORY" "$FREESPACE_REQUIRED_SOURCE"; then

				LOGFILE_OUTPUT_TEXT="[FAILED] Not enough free space in target directory $TARGET_DIRECTORY.\n - Required: $FREESPACE_REQUIRED_SOURCE MiB"
				EXIT_CODE=1

			else

				# Run, attempt to move data.
				Run_Move_Data

			fi

		fi

	fi

	#-----------------------------------------------------------------------------------
	# Print results and send to logfile
	[[ -f $FP_LOG ]] && rm $FP_LOG
	if [[ $LOGFILE_OUTPUT_TEXT ]]; then

		# Error
		if (( $EXIT_CODE )); then

			G_DIETPI-NOTIFY 1 "$LOGFILE_OUTPUT_TEXT"

		# Info
		else

			G_DIETPI-NOTIFY 2 "$LOGFILE_OUTPUT_TEXT"

		fi

		# Send to logfile
		echo -e "$LOGFILE_OUTPUT_TEXT" > $FP_LOG

	fi

	#-----------------------------------------------------------------------------------
	G_DIETPI-NOTIFY -1 $EXIT_CODE "$G_PROGRAM_NAME"
	#-----------------------------------------------------------------------------------
	exit $EXIT_CODE
	#-----------------------------------------------------------------------------------
}
